import { useCounterStore } from '@/store';

const noShowToastList = [
  'wxapp/login/getWorkerByOpenId',
  'wxapp/user/checkRechargeCardOrderIsPay',
  'wxapp/user/checkUserLevelOrderIsPay',
  'wxapp/order/checkServiceOrderIsPay',
  'wxapp/order/getDefaultUserAddress',
  'wxapp/order/checkInitialPaymentServiceOrderIsPay',
  'wxapp/login/getUserByOpenId',
  'wxapp/login/doLogin',
  'wxapp/login/getWorkerByOpenId',
  'worker/login/getWorkerByOpenId',
  'worker/login/doLogin',
];
const noLoading = [
  'wxapp/login/getWorkerByOpenId',
  'wxapp/order/checkServiceOrderIsPay',
  'wxapp/user/checkRechargeCardOrderIsPay',
  'wxapp/user/getUserCouponCount',
  'wxapp/user/checkUserLevelOrderIsPay',
  'wxapp/login/getUserByOpenId',
  'wxapp/order/checkServiceOrderIsPay',
  'wxapp/order/getDefaultUserAddress',
  'wxapp/order/checkInitialPaymentServiceOrderIsPay',
  'worker/order/getRefuseReasonListForWorker',
];

export default function request(
  url,
  data = {},
  method = 'GET',
  header = {},
  showLoading = true,
) {
  const store = useCounterStore();

  // 基础URL
  const baseUrl = 'https://adm.jinjiangservice.com/index.php/';

  // 默认请求头
  const defaultHeader = {
    'Content-Type': 'application/json',
    // 可添加token等全局参数
    // 'Authorization': uni.getStorageSync('token') || ''
  };

  // 合并请求头（用户传入的会覆盖默认的）
  const requestHeader = { ...defaultHeader, ...header };

  // 显示加载提示
  if (showLoading && !noLoading.includes(url)) {
    store.loading = true;
  }

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      method: method.toUpperCase(), // 确保方法是大写
      data: {
        ...data,
        open_id: store.open_id,
      },
      header: requestHeader,
      success: (res) => {
        // 根据实际后端约定的状态码处理
        if (res.statusCode === 200) {
          // 假设后端返回格式为 { code: 0, data: ..., msg: '' }
          if (res.data.code === 200) {
            resolve(res.data.data);
          } else {
            // 业务错误
            if (!noShowToastList.includes(url))
              uni.showToast({
                title: res.data.msg || '请求失败',
                icon: 'none',
              });
            reject(res.data);
          }
        } else {
          // HTTP状态码错误
          if (
            res.data.msg != '当前账号不存在,请注册' &&
            !noShowToastList.includes(url)
          )
            uni.showToast({
              title: `${res.data.msg}`,
              icon: 'none',
            });
          reject(res);
        }
      },
      fail: (err) => {
        // 网络错误
        uni.showToast({
          title: '网络连接失败',
          icon: 'none',
        });
        reject(err);
      },
      complete: () => {
        // 无论成功失败都关闭加载提示
        if (showLoading) {
          store.loading = false;
        }
      },
    });
  });
}
